import { useInterval, useLocalStorageState } from 'ahooks'
import { useEffect, useRef, useState } from 'react'
import { record } from 'rrweb'
import styled from 'styled-components'
import { RRDB } from '.'

const RecordSVG = () => {
	return (
		<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7497">
			<path
				d="M512 834.56a322.56 322.56 0 1 0 0-645.12 322.56 322.56 0 0 0 0 645.12zM512 896a384 384 0 1 1 0-768 384 384 0 0 1 0 768z m0-224a160 160 0 1 1 0-320 160 160 0 0 1 0 320z"
				fill="#ee6b6b"
				p-id="7498"
			></path>
		</svg>
	)
}
const StartSVG = () => {
	return (
		<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5937">
			<path d="M772.7 217.7a32.2 32.1 0 1 0 64.4 0 32.2 32.1 0 1 0-64.4 0Z" fill="#ee6b6b" p-id="5938"></path>
			<path
				d="M415.8 679.9c5.9 0 11.5-1.6 16.2-4.5l231.1-134.6c10.9-5.2 18.5-16.3 18.5-29.2 0-11.9-6.4-22.3-16-27.8L439.7 352.2c-5.8-6.7-14.4-10.9-23.9-10.9-17.6 0-31.8 14.4-31.8 32.1 0 0.6 0 1.2 0.1 1.8l-0.4 0.2 0.5 269c-0.1 1.1-0.2 2.2-0.2 3.4 0 17.7 14.3 32.1 31.8 32.1z"
				fill="#ee6b6b"
				p-id="5939"
			></path>
			<path
				d="M909.8 306.6c-5.4-10.5-16.3-17.8-28.9-17.8-17.8 0-32.2 14.4-32.2 32.1 0 6 1.7 11.7 4.6 16.5l-0.1 0.1c26.9 52.4 42.1 111.8 42.1 174.7 0 211.6-171.6 383.2-383.2 383.2S128.8 723.8 128.8 512.2 300.4 129.1 512 129.1c62.5 0 121.5 15 173.6 41.5l0.2-0.4c4.6 2.6 10 4.1 15.7 4.1 17.8 0 32.2-14.4 32.2-32.1 0-13.1-7.9-24.4-19.3-29.4C653.6 81.9 584.9 64.5 512 64.5 264.7 64.5 64.3 265 64.3 512.2S264.7 959.9 512 959.9s447.7-200.4 447.7-447.7c0-74.1-18-144-49.9-205.6z"
				fill="#ee6b6b"
				p-id="5940"
			></path>
		</svg>
	)
}

const StyledWrap = styled.div`
	position: fixed;
	top: 0;
	left: 0;
	width: 100px;
	height: 50px;
	> span {
		display: inline-block;
		width: 30px;
		margin: 10px;
		cursor: pointer;
	}
`

export const RRWeb = () => {
	const [behavior] = useLocalStorageState<string>('__EXPERIMENTAL_behavior__')
	const [start, setStart] = useState(false)
	const events = useRef<any>([])

	const setDB = () => {
		const body = JSON.stringify(events.current)
		events.current = []
		RRDB.add({ events: body })
	}

	useEffect(() => {
		let stopFn: any = null
		if (behavior === 'on' && start) {
			stopFn = record({
				emit(event) {
					events.current.push(event)
				},
			})
		} else {
			stopFn && stopFn()
			stopFn && setDB()
		}
		return () => {
			stopFn && stopFn()
			stopFn && setDB()
		}
	}, [behavior, start])

	useInterval(
		() => {
			setDB()
		},
		behavior === 'on' && start ? 10 * 1000 : undefined
	)

	return behavior === 'on' ? (
		<StyledWrap>
			<span
				onClick={() => {
					setStart((v) => !v)
				}}
			>
				{start ? <RecordSVG /> : <StartSVG />}
			</span>
		</StyledWrap>
	) : (
		<></>
	)
}
